<?php

namespace App\Controller;

use App\Model\System\User;
use Hyperf\Contract\SessionInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Logger\LoggerFactory;
use Psr\Log\LoggerInterface;
use function Hyperf\ViewEngine\view;

class LoginController extends AbstractController
{

    #[Inject]
    private SessionInterface $session;
    protected LoggerInterface $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    public function index()
    {
        $err = $this->request->input('error_warning', '');
        return view('login', ['error_warning' => $err]);
    }

    public function logout()
    {
        $this->session->clear();
        return $this->response->redirect('/login');
    }

    public function doLogin()
    {
        $data = $this->request->all();
        $user = User::where('username', $data['username'])->first();
        $err = '';

        if(!$user) {
            $err = '用户不存在';
        }elseif(!$user->status){
            $err = '该用户已被禁用';
        } else {
            $salt = trim($user->salt);
            $password = $user->password;
            $encrypt = sha1(trim($data['password']));
            $encrypt = sha1($salt.$encrypt);
            $encrypt = sha1($salt.$encrypt);
            if ($password !== $encrypt) {
                $err = '用户名或密码错误';
            }
        }

        $this->logger->info("登录信息：".$err);

        if($err) {
            return $this->response->redirect('/login?error_warning='.$err);
        } else {
            $this->logger->info('登录成功');
            $this->session->set('user_id', $user->user_id);
            return $this->response->redirect('/');
        }
    }
}